package com.homegoods.shoppingcar.ui.fragment;


import android.app.Activity;
import android.app.Fragment;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.homegoods.aroutercomment.ARouterPath;
import com.homegoods.resource.util.Utils;
import com.homegoods.shoppingcar.R;
import com.homegoods.shoppingcar.databinding.ShoppingFragmentShopCarBinding;
import com.homegoods.shoppingcar.item.GoodsItem;
import com.homegoods.shoppingcar.item.ShoppingCarEmptyItem;
import com.homegoods.shoppingcar.item.ShoppingCartItem;
import com.homegoods.shoppingcar.item.ShoppingGroupItem;
import com.homegoods.shoppingcar.presenter.OnShoppingCartChangeListener;
import com.homegoods.shoppingcar.presenter.ShoppingCartBiz;
import com.homegoods.shoppingcar.presenter.ShoppingPresenter;
import com.homegoods.shoppingcar.ui.ShopActivityMainActivity;
import com.homegoods.shoppingcar.util.DecimalUtil;
import com.kedll.library.adapter.MultiTypeAdapter;
import com.kedll.library.fragment.KRefreshListFragment;
import com.kedll.library.mvp.FooterItem;
import com.kedll.library.util.MyUtils;
import com.kedll.library.util.ViewUtil;

/**
 * A simple {@link Fragment} subclass.
 * 购物车
 *
 * @author QiQi
 */
@Route(path = ARouterPath.PATH_FRAGMENT_SHOPPING)
public class ShopCarFragment extends KRefreshListFragment<ShoppingFragmentShopCarBinding, ShoppingPresenter> {

    private boolean isEdit = false;


    /**
     * 标记当前购物车是单独的界面还是和其他Fragment一起放在首页中
     */
    private boolean singleAlone = false;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof ShopActivityMainActivity) {
            singleAlone = true;
        }
    }

    @Override
    protected ShoppingPresenter getPresenter() {
        return new ShoppingPresenter(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.shopping_fragment_shop_car;
    }

    @Override
    protected void init() {
        super.init();
        list.addItemDecoration(new SpacesItemDecoration(2, 8));
        list.getItemAnimator().setChangeDuration(0);
        list.setHasFixedSize(true);
        mBinding.fragmentToolbar.inflateMenu(R.menu.menu_edit);
        if (singleAlone) {
            mBinding.fragmentToolbar.setNavigationIcon(R.drawable.ic_arrow_back);
            mBinding.fragmentToolbar.setNavigationOnClickListener(v -> {
                getActivity().finish();
            });
        }

        mBinding.fragmentToolbar.setOnMenuItemClickListener(item -> {
            list.smoothScrollToPosition(0);
            changeEditModel(item);
            return true;
        });
    }

    /**
     * 切换编辑模式
     *
     * @param item
     */
    private void changeEditModel(MenuItem item) {
        isEdit = !isEdit;
        if (isEdit) {
            item.setTitle("完成");
            ViewUtil.setGone(mBinding.llSubmit, true);
        } else {
            item.setTitle("编辑");
            ViewUtil.setGone(mBinding.llSubmit, false);
        }
    }

    @Override
    protected void initEvent(Bundle savedInstanceState) {
        super.initEvent(savedInstanceState);
        if (singleAlone) {
            onRefresh();
        }

        mPresenter.setOnChangeListener(new OnShoppingCartChangeListener() {
            @Override
            public void onDataChange(String selectCount, String selectMoney) {
                int goodsCount = mPresenter.getGoodsCount() - 1;
                if (goodsCount == 0) {
                    mPresenter.showEmpty();
                    ShoppingCartBiz.checkItem(false, mBinding.ivSelectAll);
                    ViewUtil.setGone(mBinding.llBottom, true);
                    mBinding.fragmentToolbar.getMenu().findItem(R.id.menu).setVisible(false);
                    if (isEdit) {
                        changeEditModel(mBinding.fragmentToolbar.getMenu().findItem(R.id.menu));
                    }
                } else {
                    ViewUtil.setGone(mBinding.llBottom, false);
                    mBinding.fragmentToolbar.getMenu().findItem(R.id.menu).setVisible(true);
                    mBinding.tvCountMoney.setText(Utils.getPrice(selectMoney));
                    String rmb = DecimalUtil.multiplyWithScale(selectMoney, "0.75", 2);
                    String dy = DecimalUtil.multiplyWithScale(selectMoney, "0.25", 2);
                    mBinding.tvRmb.setText(rmb);
                    mBinding.tvDy.setText(dy);
                    mBinding.btnSubmit.setText(String.format("去结算(%s)", selectCount));
                }
            }

            @Override
            public void onSelectItem(boolean isSelectedAll) {
                ShoppingCartBiz.checkItem(isSelectedAll, mBinding.ivSelectAll);
            }
        });

        mBinding.llSelectAll.setOnClickListener(mPresenter.getListener());
        mBinding.btnSubmit.setOnClickListener(mPresenter.getListener());
        mBinding.tvDel.setOnClickListener(mPresenter.getListener());
    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return getGridLayoutManager();
    }

    @NonNull
    private RecyclerView.LayoutManager getGridLayoutManager() {
        GridLayoutManager gridLayoutManager = Utils.getGridLayoutManager(getContext(), adapter, 2);
        final GridLayoutManager.SpanSizeLookup spanSizeLookupHolder = gridLayoutManager.getSpanSizeLookup();

        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            //计算每个Item所占的跨度
            @Override
            public int getSpanSize(int position) {
                if (adapter.getItem(position) instanceof ShoppingGroupItem
                        || adapter.getItem(position) instanceof ShoppingCartItem
                        || adapter.getItem(position) instanceof GoodsItem
                        || adapter.getItem(position) instanceof ShoppingCarEmptyItem
                        ) {
                    return gridLayoutManager.getSpanCount();
                }
                if (spanSizeLookupHolder != null) {
                    return spanSizeLookupHolder.getSpanSize(position - list.getHeaderItemCount());
                }
                return 1;
            }
        });
        return gridLayoutManager;
    }


    private class SpacesItemDecoration extends RecyclerView.ItemDecoration {

        private int space;
        private int itemCount;

        public SpacesItemDecoration(int itemCount, int space) {
            this.itemCount = itemCount;
            this.space = MyUtils.dp2px(space);

        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view);
            MultiTypeAdapter.IItem iItem = adapter.getItem(position);
            if (iItem instanceof ShoppingCarEmptyItem
                    || iItem instanceof ShoppingGroupItem
                    || iItem instanceof GoodsItem
                    || iItem instanceof ShoppingCartItem
                    || iItem instanceof FooterItem) {
                outRect.set(0, 0, 0, 0);
            } else if (iItem instanceof com.homegoods.goods.item.GoodsItem) {
                outRect.bottom = space;
                //当前是推荐类商品，获取位置时，要除去购物车里的商品数量
                position = parent.getChildLayoutPosition(view) - mPresenter.getGoodsCount();
                if (position % itemCount == 0) {
                    outRect.left = 0;
                    outRect.right = space / 2;
                } else if (position % itemCount == itemCount - 1) {
                    outRect.right = 0;
                    outRect.left = space / 2;
                } else {
                    outRect.right = space / 2;
                    outRect.left = space / 2;
                }
            }
        }
    }
}
